package cmd

import (
	"os"
	"os/signal"
	"syscall"

	"gitee.com/LangHuaHuachihua/cloud-gin-manager/conf"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/protocol"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/utils"
	"github.com/spf13/cobra"
)

// var ConfigFile string

// startCmd represents the start command
var ServiceCmd = &cobra.Command{
	Use:   "start",
	Short: "天擎综合运维平台服务启动",
	// Long:  `天擎综合运维平台服务启动`,
	RunE: func(cmd *cobra.Command, args []string) error {
		//启动图
		utils.Start_log()
		//环境变量加载
		conf.Init()
		
		svc := newManager()
		// http启动

		ch := make(chan os.Signal, 1)
		defer close(ch)
		//channl 一般是发送方负责关闭
		// singal 和 waitstop ：singal在一直阻塞中直到收到信号， ch有值就会停止阻塞，就会向下发送信息，通过管道进行通信，上面接受到信号 向下传递
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
		//启动后就开始监听后台数据，到接受到关闭信号，就自动执行
		// fmt.Println("监听开始")
		go svc.waitStop(ch)
		return svc.start()

	},
}

type manager struct {
	http *protocol.HttpService
	l    *utils.Logger
}

func newManager() *manager {
	return &manager{
		http: protocol.NewHttpService(),
		l:    utils.Log(),
	}
}

func (m *manager) start() error {
	err := m.http.Start()
	if err != nil {
		return err
	}
	return err
}

func (m *manager) waitStop(ch <-chan os.Signal) {
	for v := range ch {
		switch v {
		default:
			m.l.Info("received signal %s ", v)
			err := m.http.Stop()
			if err != nil {
				return
			}

		}
	}
}

func init() {
	// ServiceCmd.PersistentFlags().StringVarP(&ConfigFile, "config", "f", "etc/demo.yaml", "demo api配置文件")
	RootCmd.AddCommand(ServiceCmd)
}
